package com.hubei.car.utils;

import com.alibaba.fastjson.JSONObject;
import com.hubei.car.entity.CarThirdUser;
import com.hubei.car.entity.HbUser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 用户工具类
 *
 * @author luokangtao
 * @create 2019-07-25 10:27
 * @author huanghaisheng
 * @update 2019-12-3
 */
@Slf4j
@Component
public class UserUtil {

    @Autowired
    JwtUtil jwtUtil;

    //获取当前登陆用户信息
    public static HbUser currentUser() {
        HbUser user = new HbUser();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        if (authorization != null) {
            //解析token
            Claims claims = new JwtUtil().parseJWT(authorization);
            //获取实体信息
            String subject = claims.getSubject();
            user = JSONObject.parseObject(subject, HbUser.class);
            log.info("解析出来的数据:{}", user);
        }
        return user;
    }

    //获取当前登陆用户信息
    public CarThirdUser getCurrentUser() {
        CarThirdUser carThirdUser = new CarThirdUser();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        if (authorization != null) {
            //解析token
            Claims claims = jwtUtil.parseJWT(authorization);
            //获取实体信息
            String subject = claims.getSubject();
            carThirdUser = JSONObject.parseObject(subject, CarThirdUser.class);
            log.info("解析出来的数据:{}", carThirdUser);
        }
        return carThirdUser;
    }

}
